package com.zeh.bill.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.zeh.bill.entity.Role;
import com.zeh.bill.entity.User;
import com.zeh.bill.entity.Vo.RoleQueryVo;
import com.zeh.bill.mapper.RoleMapper;
import com.zeh.bill.mapper.UserMapper;
import com.zeh.bill.service.RoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zeh
 * @since 2022-07-18
 */
@Service
@Transactional
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public IPage<Role> findRoleListByUserId(IPage<Role> page, RoleQueryVo roleQueryVo) {
        QueryWrapper<Role> queryWrapper = new QueryWrapper<Role>();
        queryWrapper.like(!ObjectUtils.isEmpty(roleQueryVo.getRoleName()),
                "role_name",roleQueryVo.getRoleName())
        .orderByAsc("id"); ////根据角色名称并排序
        User user = userMapper.selectById(roleQueryVo.getUserId());
        //如果用户不为空，且不是管理员，则只能查询自己创建的角色
        if(user!=null && !ObjectUtils.isEmpty(user.getIsAdmin()) && user.getIsAdmin()!=1){
             queryWrapper.eq("create_user", roleQueryVo.getUserId());
        }
        return baseMapper.selectPage(page,queryWrapper);
    }


    /**
     * 保存角色权限关系
     * @param roleId
     * @param permissionIds
     * @return
     */
    @Override
    public boolean saveRolePermission(Long roleId, List<Long> permissionIds){
        //删除该角色对应的权限信息
        baseMapper.deleteRolePermission(roleId);
        //保存角色权限
        return baseMapper.saveRolePermission(roleId,permissionIds)>0;

    }


    @Override
    public List<Long> findRoleIdByUserId(Long userId){
        return baseMapper.findRoleIdByUserId(userId);
    }


}
